package com.shelpe.services.sustainer.autoDrive;

import org.springframework.batch.item.ItemProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.shelpe.services.sustainer.client.AutoProductQueueClient;
import com.shelpe.services.sustainer.entity.jpa.AutoProductQueue;
import com.shelpe.services.sustainer.repository.jpa.AutoProductQueueRepository;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class WordChooseProcessor implements ItemProcessor<AutoProductQueueInput, AutoProductQueueResult> {

	@Autowired
	private AutoProductQueueClient autoProductQueueClient;
	@Autowired
	private AutoProductQueueRepository autoProductQueueRepository;
	
	@Override
	public AutoProductQueueResult process(AutoProductQueueInput input) throws Exception {
		AutoProductQueue.QueuePK pk = input.getPk();
		AutoProductQueue item = this.autoProductQueueRepository.findOne(pk);
		log.debug("StartWordChoose[{}]:{}", pk.getCampaignID(), item);
		
		AutoProductQueueResult res = new AutoProductQueueResult();
		res.setQueue(item);
		res.setCampaignID(pk.getCampaignID());
		res.setChunk(input.getChunk());
		if(item != null){
			if(item.getStatus() == AutoProductQueue.Status.updating && item.getProgress() == 20){
				AutoProductQueueClient.AutoDrivingDto dto = this.autoProductQueueClient.startChooseWords(item.getUserID(), item.getCampaignID(), item.getProductID());
				if(!dto.isSuccess()){
					log.error("fail to start choose words: {}", pk);
				}
				res.setStatus(dto.isSuccess()?ResultStatus.success:ResultStatus.fail);
			}else{
				log.warn("invalid status: {}", item);
				res.setStatus(ResultStatus.invalidStatus);
			}
		}else{
			res.setStatus(ResultStatus.notFound);
		}
		
		return res;
	}

}
